<template>
    <div style="padding: 12px; box-sizing: border-box;">

        <el-dialog v-model="dialogVisible" :title="formData.id ? ' 产品修改' : ' 产品新增'" width="700px">
            <el-form :inline="true" :model="formData">
                <el-form-item label="产品名称">
                    <el-input style="width: 210px;" v-model="formData.name" placeholder="产品名称" clearable />
                </el-form-item>
                <el-form-item label="产品价格">
                    <!-- <el-input style="width: 210px;" v-model="formData.price" placeholder="产品单价" clearable
                        @input="validateAmount('price')">
                        <template #suffix>
                            <el-icon>
                                元
                            </el-icon>
                        </template>
</el-input> -->
<div style="min-width: 400px;display: flex;flex-wrap: wrap;height: 100%;position: relative;bottom: 5px;">
    <el-tag
      v-for="tag in formData.price"
      :key="tag"
      closable
      style="margin-right: 10px;margin-top: 10px;"
      :disable-transitions="false"
      @close="handleClose(tag)"
    >
      {{ tag }}元
    </el-tag>
    <el-input
      v-if="inputVisible"
      ref="InputRef"
      v-model="inputValue"
      style="width: 80px;margin-top: 10px;"
      size="small"
      @keyup.enter="handleInputConfirm"
      @blur="handleInputConfirm"
       @input="handleNumberInput"
    />
    <el-button v-else class="button-new-tag" style="margin-right: 10px;margin-top: 10px;" type="info" size="small" @click="showInput">
      新增价格
    </el-button>
  </div>
                </el-form-item>
                <el-form-item label="产品单位">
                    <el-input style="width: 210px;" v-model="formData.unit" placeholder="产品单位" clearable />
                </el-form-item>
                <el-form-item label="产品备注">
                    <el-input style="width: 520px;" type="textarea" v-model="formData.desc" placeholder="产品备注"
                        clearable />

                </el-form-item>
            </el-form>

            <template #footer>
                <div>
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button @click="onSubmit" type="primary">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <sDialog :content="scontent" ref="sdialog" :confirmFunction="confirmFunction"></sDialog>
        <el-card style="width: 100%;">
            <el-form :inline="true" style="margin-top: 20px;" :model="queryParams">
                <el-form-item label="产品名称">
                    <el-input v-model="queryParams.name" placeholder="请输入产品名称" clearable />
                </el-form-item>

                <el-form-item>
                    <el-button @click="handleQuery" v-hasPermiss="rolepathName('search')" type="primary">搜索</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card style="width: 100%;margin-top:10px">
            <template #header>
                <div style="display: flex;align-items: center;justify-content: space-between;">
                    <span> 产品列表</span>
                    <el-button @click="handleForm()" v-hasPermiss="rolepathName('add')" type="primary">新增</el-button>
                </div>
            </template>
            <el-table :data="listInfo.list" style="width: 100%; margin-bottom: 20px" default-expand-all row-key="_id"
                border>

                <el-table-column align="center" prop="name" label="产品名称" />
                <el-table-column align="center" prop="price" label="产品单价" >
                    <template #default="scope">
                  <el-space> <el-tag v-for="tag in scope.row.price" :key="tag">{{ tag }}元</el-tag></el-space>
                      
                                          
                        </template>
              
                </el-table-column>
                <el-table-column align="center" prop="unit" label="产品单位" />
                <el-table-column align="center" prop="desc" label="产品描述">
                    <template #default="scope">
                        <el-tooltip effect="dark" placement="top">
                            <template #content>
                                <div style="width: 600px;height: auto;">{{ scope.row.desc }}</div>
                            </template>
                            <span style="cursor: pointer;">{{ scope.row.desc?.length > 30 ? scope.row.desc.substr(0,
                                30) + '...' : scope.row.desc
                            }}</span>
                        </el-tooltip>
                    </template>


                </el-table-column>

                <el-table-column align="center" label="操作">
                    <template #default="scope">
                        <el-space wrap>
                            <el-button size="small" @click="handleForm(scope.row._id)" v-hasPermiss="rolepathName('put')" type="primary">编辑</el-button>
                            <el-button size="small" v-hasPermiss="rolepathName('delete')" @click="deletem(scope.row._id)" type="danger">删除</el-button>
                        </el-space>
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <div style="display: flex;justify-content: center;">
                    <el-pagination :page-sizes="[10, 20, 50, 100]" layout="sizes, prev, pager, next" @size-change="sc"
                        @current-change="cc" v-model:current-page="listInfo.cpage" v-model:page-size="listInfo.pageSize"
                        background :total="listInfo.total" />
                </div>
            </template>
        </el-card>

    </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance,nextTick } from "vue"
import { resetAble } from "../../composable/reset"
import { ElMessage } from "element-plus";
import { addProduct, getProductList, getProduct, delProduct, putProduct } from "../../api/product";
import sDialog from "../../components/sDialog.vue";
import { rolepathName } from "../../composable/dealname";
const { proxy } = getCurrentInstance() as any
const dialogVisible = ref(false)
const inputVisible = ref(false)
const inputValue = ref('')
const InputRef = ref<HTMLInputElement>()
const { data: queryParams, reset: resetQueryParams } = resetAble({
    name: "",
    desc: "",
}) as any
const handleNumberInput = (value: string) => {
    inputValue.value = value.replace(/[^\d.]/g, '')  // 只允许数字和小数点
}

const handleInputConfirm = () => {
    if (inputValue.value) {
        // 验证是否为合法数字
        if (!/^\d+(\.\d+)?$/.test(inputValue.value)) {
            ElMessage.error('请输入有效的数字格式')
            return
        }
        formData.value.price.push(inputValue.value)
    }
    inputVisible.value = false
    inputValue.value = ''
}

const handleClose = (tag: string) => {
    formData.value.price.splice(formData.value.price.indexOf(tag), 1)
}

const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
        InputRef.value?.focus()
    })
}
const listInfo = ref({
    list: [],
    total: 0,
    cpage: 1,
    pageSize: 10
})

const handleQuery = () => {

    init().then(() => {
        ElMessage({
            message: '查询成功',
            grouping: true,
            type: 'success',
        })
    })
}
const handleReset = () => {
    resetQueryParams()
    init().then(() => {
        ElMessage({
            message: '重置成功',
            grouping: true,
            type: 'success',
        })
    })
}
const sc = (e: any) => {

    listInfo.value.pageSize = e
    init()
}
const cc = (e: any) => {

    listInfo.value.cpage = e
    init()
}

const scontent = ref('')
const confirmFunction = () => {
    confirmDelete()
}
const handleForm = async (id?: string) => {

    if (id) {

        let res = await getProduct({ id })
        formData.value = res.data
        formData.value.id = id
    } else {

        reset()
    }
    dialogVisible.value = true
}






const { data: formData, reset } = resetAble({
    name: "",
    desc: "",
    price: [],
    unit: "",

}) as any
const deletem = (id: string) => {
    formData.value.id = id
    scontent.value = '确定要删除该产品吗？'
    proxy.$refs.sdialog.showCenterDialog = true
}

const confirmDelete = () => {
    delProduct({ id: formData.value.id }).then((res: any) => {
        if (res) {
            ElMessage({
                message: '操作成功',
                grouping: true,
                type: 'success',
            })
            init()
        }
    })

}

const onSubmit = async () => {


    if (formData.value.id) {
        let res = await putProduct(formData.value) as any
        if (res) {
            init()
            ElMessage({
                message: '修改成功',
                grouping: true,
                type: 'success',
            })
        }
    } else {

        let res = await addProduct(formData.value) as any
        if (res) {
            init()
            ElMessage({
                message: '操作成功',
                grouping: true,
                type: 'success',
            })
        }
    }
    dialogVisible.value = false
}

const init = () => {
    return new Promise<void>((resolve, reject) => {
        getProductList({
            data: queryParams.value,
            params: {
                currentPage: listInfo.value.cpage,
                pageSize: listInfo.value.pageSize
            }
        }

        ).then((res) => {
            if (res) {
                listInfo.value.list = res.data.list
                listInfo.value.total = res.data.total
            }
            resolve()
        }).catch(err => {
            reject(err)
        })
    })
}

init()
</script>
<style lang="scss" scoped>
:deep(.el-icon) {
    font-style: normal;
    font-weight: bolder;
}
</style>